package com.ali.biofiletransfer;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class BIOFileTransferClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 8080);
            String fileName = "C:\\Users\\Administrator\\Desktop\\test.mobi";
            long startTime = System.currentTimeMillis();
            long total = sendFile(socket, fileName);
            long endTime = System.currentTimeMillis();
            System.out.println("耗时：" + (endTime - startTime) + "，发送字节数：" + total);
            //关闭客户端连接
            socket.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送文件
     */
    private static long sendFile(Socket socket, String fileName) {
        byte[] bytes = new byte[1024];
        int length;
        int total = 0;
        //构建文件输入流
        //获取文件输出流
        try (FileInputStream fileInputStream = new FileInputStream(fileName); OutputStream outputStream = socket.getOutputStream()) {
            while (true) {
                length = fileInputStream.read(bytes);
                if (length > 0) {
                    outputStream.write(bytes, 0, length);
                    total = total + length;
                } else {
                    break;
                }
            }
            return total;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
